package fr.noe.amicaleloisirs.concours.view;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextBox;

import fr.noe.amicaleloisirs.concours.business.Concours;
import fr.noe.amicaleloisirs.concours.business.Match;
import fr.noe.amicaleloisirs.concours.client.Belote;
import fr.noe.amicaleloisirs.concours.utils.Logger;

public class MatchsPanel extends FlowPanel {

    private Concours concours;
    private Label numeroPartie;
    private final Button validerButton = new Button("Valider");
    private final List<MatchView> matchView = new ArrayList<MatchsPanel.MatchView>();

    public MatchsPanel(final Concours c) {
    	super();
    	log("start()");
        concours = c;
        numeroPartie = new Label("Partie " + c.getIntTour());
        
        numeroPartie.setStyleName("numeroPartie");
        this.add(numeroPartie);
        for (Match m : c.getMatches()) {
            this.add(new MatchView(m).getView());
        }
        validerButton.addStyleName("withMargin");
        validerButton.addClickHandler(new ClickHandler() {

            @Override
            public void onClick(ClickEvent event) {
                int res = isValide();
                log("Validation des résultats, code retour : " + res);
                if (res == 0) {
                    for (MatchView m : matchView) {
                        int score1 = 0;
                        int score2 = 0;
                        if ((m.match.getT1() != null) && (m.match.getT2() != null)) {
                        	score1 = Integer.parseInt(m.score1.getValue());
                        	score2 = Integer.parseInt(m.score2.getValue());
                        }
                        m.match.setMatchResult(score1, score2);
                    }
                    Belote.get().displayClassement();
                } else {
                    String text = (res == 1 ? "Tous les scores ne sont pas remplis"
                            : "Un ou plusieurs score(s) est/sont invalide(s)");
                    new InfoPopUp(text, new ClickHandler() {

                        @Override
                        public void onClick(ClickEvent event) {
                        }
                    });
                }
            }
        });
        this.add(validerButton);
    }

    /**
     * 0: ok 1: pas tous les champs remplis 2: une valeur n'est pas un nombre
     */
    private int isValide() {
        int res = 0;
    	for (MatchView match : matchView) {
            if (match.match.getT1() != null && match.match.getT2() != null) {
                try {
                    if (!match.score1.getValue().isEmpty()
                            && !match.score2.getValue().isEmpty()) {
                        Integer.parseInt(match.score1.getValue());
                        Integer.parseInt(match.score2.getValue());
                    } else {
                        return 1;
                    }
                } catch (NumberFormatException e) {
                    return 2;
                }
            }
        }
        return res;
    }

    public class MatchView {

        private Label equipe1;
        private Label equipe2;
        public final TextBox score1 = new TextBox();
        public final TextBox score2 = new TextBox();
        private HorizontalPanel container;
        public Match match;

        public MatchView(Match m) {
            match = m;
            container = new HorizontalPanel();
            equipe1 = new Label();
            equipe2 = new Label();
            equipe1.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
            equipe2.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
            equipe1.setStyleName("equipe");
            equipe2.setStyleName("equipe");
            if (m.getT1() == null) {
            	equipe1.setText("Exempt");
            	score1.setEnabled(false);
            	score2.setEnabled(false);
            }
            else {
            	equipe1.setText(m.getT1().getPlayer1().getFirstname() + " "
                        + m.getT1().getPlayer1().getLastname() + " / "
                        + m.getT1().getPlayer2().getFirstname() + " "
                        + m.getT1().getPlayer2().getLastname());
            }
            if (m.getT2() == null) {
            	equipe2.setText("Exempt");
            	score1.setEnabled(false);
            	score2.setEnabled(false);
            }
            else {
	            equipe2.setText(m.getT2().getPlayer1().getFirstname() + " "
	                    + m.getT2().getPlayer1().getLastname() + " / "
	                    + m.getT2().getPlayer2().getFirstname() + " "
	                    + m.getT2().getPlayer2().getLastname());
            }

            score1.setMaxLength(4);
            score2.setMaxLength(4);
            score1.setStyleName("textBoxScore");
            score2.setStyleName("textBoxScore");

            KeyPressHandler kph = new KeyPressHandler() {

                @Override
                public void onKeyPress(KeyPressEvent event) {
                    if (!Character.isDigit(event.getCharCode())
                            && (event.getUnicodeCharCode() != 0)) {
                        ((TextBox) event.getSource()).cancelKey();
                    }
                }
            };

            score1.addKeyPressHandler(kph);
            score2.addKeyPressHandler(kph);
            container.add(equipe1);
            container.add(score1);
            container.add(new HTML(" - "));
            container.add(score2);
            container.add(equipe2);

            matchView.add(this);
        }

        public HorizontalPanel getView() {
            return container;
        }
    }
    
    private static void log(String text) {
		Logger.get().logWithClass("MatchsPanel", text);
	}
}

